﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using NewsCrawler.Common.Interfaces;
using NewsCrawler.Common.Models;

namespace CrawlerManager
{
    public class Core
    {
        private static Core m_Instance = null;
        private static object m_LockObject = new object();

        public static Core Instance
        {
            get
            {
                if (m_Instance != null)
                    return m_Instance;
                lock (m_LockObject)
                {
                    if (m_Instance == null)
                        m_Instance = new Core();
                }
                return m_Instance;
            }
        }

        public void RunPipeLines()
        {
            List<Article> allArticles = GetAllArticles();
            allArticles.ForEach((a) =>
                                    {
                                        a.Parser.Parse(a);
                                        DBManager.Write(a);
                                    });
        }

        private List<Article> GetAllArticles()
        {
            List<Article> allArticles = new List<Article>();
            List<Assembly> assemblies = CrawlerHelper.GetAssemblies();
            assemblies.ForEach
                (
                    (assembly) =>
                        {
                            ICrawler crawler = CreateCrawler(assembly);
                            List<Article> articles = crawler.Parse();
                            allArticles.AddRange(articles);
                        }
                );

            return allArticles;
        }

        public ICrawler CreateCrawler(Assembly assembly)
        {
            return CrawlerFactory.CreateCrawler(assembly);
        }
    }
}
